package com.explorati.LeetCode349.insersection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 349. Intersection of Two Arrays
 * 
 * Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
 * 
 * @author explorati
 *
 */
public class Solution {

	public static int[] intersection(int[] nums1, int[] nums2) {
		Set<Integer> set = new HashSet<>();
		for (int i = 0; i < nums1.length; i++) {
			set.add(nums1[i]);
		}

		Set<Integer> set1 = new HashSet<>();
		for (int i = 0; i < nums2.length; i++) {
			if (set.contains(nums2[i])) {
				set1.add(nums2[i]);
			}
		}
		List<Integer> list = new ArrayList<>();
		Iterator iter = set1.iterator();
		while(iter.hasNext()) {
			list.add((Integer) iter.next());
		}
		int[] res = new int[list.size()];
		for (int i = 0; i < list.size(); i++) {
			res[i] = list.get(i);
		}
		return res;
	}

	public static void main(String[] args) {
		int[] nums1 = { 4, 9, 5 };
		int[] nums2 = { 9, 4, 9, 8, 4 };

		int[] res = intersection(nums1, nums2);
		for (int i : res) {
			System.out.print(i + "  ");
		}
	}
}
